import React from 'react';
import { Tag, Input, Tooltip, Button } from 'antd';

class EditableTagGroup extends React.Component {
  state = {
    inputVisible: false,
    inputValue: '',
    value: ['示例属性1', '示例属性2'],
  };

  handleClose = (removedTag) => {
    const value = this.state.value.filter(tag => tag !== removedTag);
    console.log(value);
    this.setState({ value });
  }

  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  }

  handleInputChange = (e) => {
    this.setState({ inputValue: e.target.value });
  }

  handleInputConfirm = () => {
    const state = { ...this.state };
    const inputValue = { ...state.inputValue };
    let value = { ...state.value };
    if (inputValue && value.indexOf(inputValue) === -1) {
      value = [...value, inputValue];
    }

    this.props.updateValue(value);

    this.setState({
      value,
      inputVisible: false,
      inputValue: '',
    });
  }

  saveInputRef = (input) => {
    this.input = input;
  }

  render() {
    const { value, inputVisible, inputValue } = this.state;
    return (
      <div>
        {value.map((tag, index) => {
          const isLongTag = tag.length > 20;
          const tagElem = (
            <Tag key={tag} closable={index >= 0} afterClose={() => this.handleClose(tag)}>
              {isLongTag ? `${tag.slice(0, 20)}...` : tag}
            </Tag>
          );
          return isLongTag ? <Tooltip title={tag} name={tag}>{tagElem}</Tooltip> : tagElem;
        })}
        {inputVisible && (
          <Input
            ref={this.saveInputRef}
            type="text"
            size="small"
            style={{ width: 78 }}
            value={inputValue}
            onChange={this.handleInputChange}
            onBlur={this.handleInputConfirm}
            onPressEnter={this.handleInputConfirm}
          />
        )}
        {!inputVisible && <Button size="small" type="dashed" onClick={this.showInput}>+ 新增属性</Button>}
      </div>
    );
  }
}

export default EditableTagGroup;
